<template>
  <div class="scatter-css" style="width:100;height:100%" :id="id">
    <Portal to="right-disable" style="width:100%;height:100%;"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  style="width:100%;height: 100%;border:0">
        <el-card shadow="never"
                 class="el-card content-card"
                 style="width:100%;height: 100%;border:0">
          <div style="width:100%;height:100%;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <div>
                <MoreMenu :slicer='slicer'
                          :fitToHeight='fitToHeight'
                          :gadgetId='id'
                          :gadgetType='gadgetInfo.com'
                          @updateQuery="query"
                          :widgetName="widgetName"
                          :businessType="gadgetInfo.businessType"
                          :id="gadgetInfo.id"
                          @showQueryModel="showQueryModel"
                          @fullScreen="fullScreen" />
              </div>
          </div>
          <div class='control-section control-section2'>
            <div class=content-wrapper
               style="width:100%;height:100%">
            <div v-if="isHasData"
                :key="isHasData"
                 :id="selfGadgetUuid"
                 style="width:100%;height:100%;"
                 :style="{'zoom':1}"></div>
            <div v-else
                  class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
            </div>
          </div>
          </div>
        </div>
      </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import * as Echarts from 'echarts'
import { getUUID } from '@/utils'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'

export default ({
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      selfGadgetUuid: getUUID(),
      currentTime: null,
      queryData: [],
      queryFields: [],
      gadgetSetting: null,
      loading: false,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'scattergadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'scattergadget' }).gadgetSetting
        }
      },
      chartWidth: '500',
      chartHeight: '500',
      queryId: '',
      queryDrillthrough: {},
      widgetName: '',
      chartDom: null,
      repeatNumber: 0,
      gadgetWidth: null,
      chart: null,
      itemStyle: {
        opacity: 0.8,
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowOffsetY: 0,
        shadowColor: 'rgba(0,0,0,0.3)'
      },
      echartsOption: {
        title: {},
        color: [
          '#dd4444', '#fec42c', '#80F1BE'
        ],
        legend: {
          top: 10,
          data: [''],
          textStyle: {
            fontSize: 16
          }
        },
        grid: {
          // top: '10px',
          left: '10px',
          right: '10px',
          bottom: '20px',
          width: '94%',
          // height: '85%',
          containLabel: true
        },
        tooltip: {
          backgroundColor: ['rgba(255,255,255,0.7)']
        },
        xAxis: {
          type: 'value',
          name: '',
          nameLocation: 'center',
          // nameGap: 16,
          // nameTextStyle: {
          //   fontSize: 16
          // },
          max: 100,
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '',
          nameLocation: 'end',
          // nameGap: 20,
          // nameTextStyle: {
          //   fontSize: 16,
          //   padding: [0, 0, 0, 50]
          // },
          splitLine: {
            show: false
          }
        },
        visualMap: [
          {
            left: 'right',
            top: '10%',
            dimension: 2,
            min: 0,
            max: 10,
            itemWidth: 30,
            itemHeight: 120,
            calculable: true,
            precision: 0.1,
            text: [],
            textGap: 30,
            inRange: {
              symbolSize: [10, 70]
            },
            outOfRange: {
              symbolSize: [10, 70],
              color: ['rgba(255,255,255,0.4)']
            },
            controller: {
              inRange: {
                color: ['#c23531']
              },
              outOfRange: {
                color: ['#999']
              }
            }
          }
        ],
        series: [
          {
            name: '',
            type: 'scatter',
            itemStyle: null,
            data: null
          }
        ]
      },
      linkedDatasetList: []
    }
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    // this.gadgetHeight = (this.gadgetInfo.h * 20) - 45
    // this.query()
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  updated () {
    if (document.getElementById(`${this.selfGadgetUuid}`) && document.getElementById(`${this.selfGadgetUuid}`).offsetWidth) {
      let wW = document.getElementById(`${this.selfGadgetUuid}`).offsetWidth
      let wH = document.getElementById(`${this.selfGadgetUuid}`).offsetHeight
      this.gadgetSetting.titleFontSize = (parseInt(wW / 70) + parseInt(wH / 200))<10?'10px':(parseInt(wW / 70) + parseInt(wH / 200) + 'px')
    }
  },
  methods: {
    updateChart (originData) {
      this.chartDom = document.getElementById(`${this.selfGadgetUuid}`)
      if (!this.chartDom) {
        setTimeout(() => {
          this.repeatNumber++
          this.updateChart(originData)
        }, 1000)
      } else {
        this.gadgetWidth = this.chartDom.clientWidth
        let myChart = Echarts.init(this.chartDom, this.globalTheme)
        this.echartsOption.tooltip.formatter = (obj) => {
          var value = obj.value
          return '<div style="text-align:left;border-bottom: 1px solid rgba(255,255,255,.3); font-size: 18px;padding-bottom: 7px;margin-bottom: 7px">' +
            this.setFormatFunctionForChart(this.queryFields, value[3], this.gadgetSetting.valueFieldsNamegroupby) + '</div>' +
            '<div style="text-align:left">' + this.gadgetSetting.valueFieldsNamexAxis + '：' + this.setFormatFunctionForChart(this.queryFields, value[0], this.gadgetSetting.valueFieldsNamexAxis) + '</div>' +
            '<div style="text-align:left">' + this.gadgetSetting.valueFieldsNameyAxis + '：' + this.setFormatFunctionForChart(this.queryFields, value[1], this.gadgetSetting.valueFieldsNameyAxis) + '</div>' +
            '<div style="text-align:left">' + this.gadgetSetting.valueFieldsNamegradius + '：' + this.setFormatFunctionForChart(this.queryFields, value[2], this.gadgetSetting.valueFieldsNamegradius) + '</div>'
        }
        this.echartsOption.title.textStyle = { fontSize: this.gadgetSetting.titleFontSize || 18 }
        this.echartsOption.series[0].data = originData
        this.echartsOption.xAxis.max = this.gadgetSetting.maximum
        this.echartsOption.xAxis.name = this.gadgetSetting.valueFieldsNamexAxis
        this.echartsOption.yAxis.name = this.gadgetSetting.valueFieldsNameyAxis
        this.echartsOption.visualMap[0].text = [this.gadgetSetting.valueFieldsNamegradius]
        this.echartsOption.series[0].itemStyle = this.itemStyle
        this.echartsOption.series[0].name = this.gadgetSetting.valueFieldsNamegroupby
        this.echartsOption.legend.data = [this.gadgetSetting.valueFieldsNamegroupby]
        myChart.setOption(this.echartsOption)

        myChart.on('click', params => {
          if (!params.name) {
            params.name = params.value[3]
          }
          this.setDrillThroughInfo(params)
        })
        this.$erd.listenTo(this.chartDom, element => {
          this.$nextTick(() => {
            this.resized()
          })
        })
        this.chart = myChart
        this.loading = false
        this.updateGadgetLoadingStatus(!this.loading)
      }
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = (newWPx - 5) + 'px'
      this.chartHeight = (newHPx - 5) + 'px'
    },
    onClick (val) {
      let data = ''
      if (this.queryDrillthrough.dataType === 'dimension') {
        data = '"' + this.queryDrillthrough.field + '"' + "='" + val + "'"
      }
      this.findOriginData(data)
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      setTimeout(() => {
        let myChart = Echarts.init(this.chartDom, this.globalTheme)
        myChart.resize()
      }, 0)
    },
    query (e) {
      if (e !== 'auto') {
        this.loading = true
        this.gadgetSetting = this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        _self.verifyHasData(res)
        try {
          _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
        } catch (error) {

        }
        if (res.config) {
          _self.gadgetSetting = _self._.merge(_self.gadgetSetting, res.config)
        }
        if (!_self.gadgetSetting.headerDescription || _self.gadgetSetting.headerDescription === null) {
          _self.gadgetSetting.headerDescription = ''
        }
        this.fxFields = res.fxFields || []
        if (res.name) {
          _self.widgetName = res.name
        } else if (this.wName) {
          _self.widgetName = this.wName
        } else {
          _self.widgetName = _self.gadgetSetting.headerTitle
        }
        let objList = res.selectFields.find(item => { return item.dataType === 'dimension' })
        _self.queryDrillthrough = objList || {}
        _self.queryId = _self.queryDrillthrough ? _self.queryDrillthrough.queryId : ''
        _self.queryData = res.data
        _self.queryFields = res.selectFields
        for (var i = 0; i < res.data.length; i++) {
          res.data[i] = [res.data[i][this.gadgetSetting.valueFieldsNamexAxis], res.data[i][this.gadgetSetting.valueFieldsNameyAxis], res.data[i][this.gadgetSetting.valueFieldsNamegradius], res.data[i][this.gadgetSetting.valueFieldsNamegroupby]]
        }
        _self.linkedDatasetList = res.datasetSync
        _self.updateChart(res.data)
      }).catch((error) => {
        if (this.wName) {
          this.widgetName = this.wName
          }
        Echarts.init(this.chartDom).dispose()
        this.isHasData = false
        this.loading = false
        if (error.response && error.response.status === 504) {
          this.errorStatus = '504'
          this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
        }
      }).finally(() => {
        this.currentTime = new Date()
        this.autoRefreshQuery(e)
        this.updateGadgetLoadingStatus(!this.loading)
      })
    }
  }
})
</script>
<style lang="scss" scoped>
.content-card {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 45%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
  width: 100% !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.valuecss {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  z-index: 50;
  display: flex;
  justify-content: center;
  align-items: center;
}

.title {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
  padding: 5px;
}

.el-card {
  padding: 0 !important;
}

#circulargauge_control_1_CircularGaugeBorder {
  height: 100%;
}
</style>
<style lang="scss">
.scatter-css {
  .el-card__body {
    width: 100%;
    height: 100%;
  }
  .control-section2 {
    width: 100%;
    height: calc(100% - 34px);
  }
}
</style>
